package com.heima.comment.service.impl;

import com.heima.apis.article.IArticleClient;
import com.heima.apis.user.IUserClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.CommentVo;
import com.heima.comment.service.CommentService;
import com.heima.common.constants.KafkaConstants;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IWemediaClient iWemediaClient;

    @Autowired
    private IUserClient iUserClient;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 加载用户评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询评论
        List<ApComment> apComments = mongoTemplate.find(Query
                .query(Criteria.where("entryId")
                        .is(dto.getArticleId())
                        .and("createdTime")
                        .lt(dto.getMinDate()))
                .limit(10)
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApComment.class);

        //判断用户是否登录
        Integer userID = AppThreadLocalUtil.getUserID();
        if (userID == null) {
            return ResponseResult.okResult(apComments);
        }
        //判断用户是否点赞
        List<CommentVo> commentVos = apComments.stream().map(comment -> {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(comment, commentVo);
            long count = mongoTemplate.count(Query
                    .query(Criteria.where("commentId")
                            .is(comment.getId())
                            .and("authorId").is(userID)), ApCommentLike.class);
            commentVo.setOperation((short) (count > 0 ? 0 : 1));
            return commentVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(commentVos);
    }

    /**
     * 发布评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(CommentSaveDto dto) {
        //校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否登录
        Integer userID = AppThreadLocalUtil.getUserID();
        if (userID == null || userID == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "必须登录后才能发表评论");
        }
        Boolean isComment = iArticleClient.getIsComment(dto.getArticleId());
        if (!isComment) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论功能已关闭无法评论");
        }
        //判断评论字数
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        //审核用户评论
        if (!iWemediaClient.scanText(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不合规");
        }
        //获取用户名称
        //添加评论到数据库
        ApComment apComment = new ApComment();
        apComment.setContent(dto.getContent());
        apComment.setAuthorId(userID);
        apComment.setCreatedTime(new Date());
        apComment.setFlag(0);
        apComment.setEntryId(dto.getArticleId());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setAuthorName(iUserClient.getName(userID));
        apComment.setType((short) 0);
        mongoTemplate.save(apComment);
        //使用kafka发送异步请求增加评论数量
        kafkaTemplate.send(KafkaConstants.ADD_COMMENT,dto.getArticleId().toString());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //校验参数
        if (dto == null || dto.getOperation() == null || StringUtils.isBlank(dto.getCommentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改数据库数据
        //判断用户是否登录
        Integer userID = AppThreadLocalUtil.getUserID();
        if (userID == null || userID == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "必须登录后才能点赞");
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment != null && dto.getOperation() == 0) {
            //保存评论点赞数据
            ApCommentLike apCommentLike=new ApCommentLike();
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setAuthorId(userID);
            mongoTemplate.save(apCommentLike);
            //更新评论点赞数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
        } else if (apComment != null && dto.getOperation() == 1) {
            //删除评论点赞数据
            mongoTemplate.remove(Query.query(Criteria.where("commentId")
                    .is(apComment.getId())
                    .and("authorId")
                    .is(userID)), ApCommentLike.class);
            //更新评论点赞数量
            apComment.setLikes(Math.max(apComment.getLikes() - 1, 0));
            mongoTemplate.save(apComment);
        }
        //封装点赞数量
        Map<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }
}
